package com.ctrip.demo.lock;

import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExchangerTest {

    public static void main(String[] args) {

        /**
         * 线程pool-1-thread-1正在把数据a换出去
         * 线程pool-1-thread-2正在把数据b换出去
         * 线程pool-1-thread-2换回的数据为a
         * 线程pool-1-thread-1换回的数据为b
         *
         *
         *
         * 线程pool-1-thread-2正在把数据b换出去
         * 线程pool-1-thread-1正在把数据a换出去
         * 线程pool-1-thread-1换回的数据为b
         * 线程pool-1-thread-2换回的数据为a
         */
        ExecutorService service = Executors.newCachedThreadPool();
        final Exchanger exchanger = new Exchanger();
        service.execute(new Runnable(){
            @Override
            public void run() {
                try {
                    Thread.sleep((long)(Math.random()*10000));
                    String data1 = "a";
                    System.out.println("线程" + Thread.currentThread().getName() +
                            "正在把数据" + data1 +"换出去");
                    String data2 = (String)exchanger.exchange(data1);
                    System.out.println("线程" + Thread.currentThread().getName() +
                            "换回的数据为" + data2);
                }catch(Exception e){

                }
            }
        });
        service.execute(new Runnable(){
            @Override
            public void run() {
                try {
                    Thread.sleep((long)(Math.random()*10000));
                    String data1 = "b";
                    System.out.println("线程" + Thread.currentThread().getName() +
                            "正在把数据" + data1 +"换出去");
                    String data2 = (String)exchanger.exchange(data1);
                    System.out.println("线程" + Thread.currentThread().getName() +
                            "换回的数据为" + data2);
                }catch(Exception e){

                }
            }
        });

        service.execute(new Runnable(){
            @Override
            public void run() {
                try {
                    Thread.sleep((long)(Math.random()*10000));
                    String data1 = "c";
                    System.out.println("线程" + Thread.currentThread().getName() +
                            "正在把数据" + data1 +"换出去");
                    String data2 = (String)exchanger.exchange(data1);
                    System.out.println("线程" + Thread.currentThread().getName() +
                            "换回的数据为" + data2);
                }catch(Exception e){

                }
            }
        });
        service.shutdown();
    }

}
